//
// Created by de on 3/31/21.
//

#include <sstream>
#include "MySqlDaoImpl.h"
#define DEFAULT_URI "tcp://localhost"
#define EXAMPLE_USER "tt"
#define EXAMPLE_PASS "123456"
#define EXAMPLE_DB "test"

#define DEFAULT_DATABASE "City"

using namespace sql;

#include "mysqlx/xdevapi.h"


using ::std::cout;
using ::std::endl;
using namespace ::mysqlx;


MySqlDaoImpl::MySqlDaoImpl() {
   driver = sql::mysql::get_driver_instance();
}

void MySqlDaoImpl::insertObject() {

}

bool MySqlDaoImpl::connect() {

    bool ret = true;

    try{
        p_conn = std::shared_ptr<Connection >(driver->connect(DEFAULT_URI, EXAMPLE_USER, EXAMPLE_PASS));
        spdlog::info("Sql connnect is ready");

        std::cout<< p_conn->isValid() <<std::endl;
        spdlog::info(p_conn->isValid());
        p_conn->setSchema(EXAMPLE_DB);


        spdlog::info("Sql connnect is sucessfullly");

    }catch (sql::SQLException &e)
    {
        std::ostringstream os;
        os<< "Sql connnect is fail , Error code "<<e.what();
        spdlog::error(os.str());
        ret = false;
    }

    return ret;

}

void MySqlDaoImpl::disconnect() {
    if(p_conn->isValid() && !p_conn->isClosed())
        p_conn->close();

    spdlog::info("Sql disconnect");

}

void MySqlDaoImpl::selectObject() {

}

bool MySqlDaoImpl::checkDataBaseExist() {

    bool IsExist = false;

    std::ostringstream os;
    os<< "SELECT table_name FROM information_schema.TABLES WHERE table_name = " <<DEFAULT_DATABASE<<";";

    std::unique_ptr< sql::Statement > stmt(p_conn->createStatement());

    try {
        std::unique_ptr< sql::ResultSet >  res(stmt->executeQuery(os.str()));
        while (res->next())
        {
            os.clear();
            os<< DEFAULT_DATABASE << " is exist ";
            spdlog::info(os.str());
            IsExist = true;
            break;
        }
    }catch (sql::SQLException &e)
    {
        spdlog::error(e.what());
    }

    return IsExist;
}

void MySqlDaoImpl::selectProperty(const std::string &Property, std::string & result) {

    std::unique_ptr< sql::Statement > stmt(p_conn->createStatement());
    std::ostringstream os;
    os << "SELECT *  from " <<DEFAULT_DATABASE<<";";

    std::unique_ptr< sql::ResultSet >  res(stmt->executeQuery(os.str()));

    while (res->next())
    {
        cout << "\t... MySQL replies: " << res->getString("CityName") << endl;
    }
}

void MySqlDaoImpl::insert() {

}

void MySqlDaoImpl::remove() {

}

void MySqlDaoImpl::removeAllInfo() {

}

bool MySqlDaoImpl::checkTableExist() {
    return checkDataBaseExist();
}
